<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="货道编号" prop="channelCode">
        <el-input
          v-model="queryParams.channelCode"
          placeholder="请输入货道编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="innerCode">
        <el-input
          v-model="queryParams.innerCode"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备ID" prop="vmId">
        <el-select v-model="queryParams.vmId" placeholder="请选择设备" clearable>
          <el-option
            v-for="item in vmList"
            :key="item.id"
            :label="item.innerCode + ' - ' + item.vmTypeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:channel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:channel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:channel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:channel:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="channelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="货道ID" align="center" prop="id" />
      <el-table-column label="货道编号" align="center" prop="channelCode" />
      <el-table-column label="设备编号" align="center" prop="innerCode" />
      <el-table-column label="最大容量" align="center" prop="maxCapacity">
        <template #default="scope">
          <el-tag>{{ scope.row.maxCapacity }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="当前容量" align="center" prop="currentCapacity">
        <template #default="scope">
          <el-progress
            :percentage="Math.round((scope.row.currentCapacity / scope.row.maxCapacity) * 100)"
            :color="getProgressColor(scope.row.currentCapacity, scope.row.maxCapacity)"
            :stroke-width="12"
          />
          <span class="ml-2">{{ scope.row.currentCapacity }}/{{ scope.row.maxCapacity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="容量状态" align="center">
        <template #default="scope">
          <el-tag :type="getCapacityStatus(scope.row.currentCapacity, scope.row.maxCapacity)">
            {{ getCapacityText(scope.row.currentCapacity, scope.row.maxCapacity) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上次补货时间" align="center" prop="lastSupplyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastSupplyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:channel:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:channel:remove']"
          >删除</el-button>
          <el-button
            link
            type="warning"
            icon="RefreshLeft"
            @click="handleSupply(scope.row)"
            v-hasPermi="['manage:channel:edit']"
          >补货</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通道管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="channelRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="货道编号" prop="channelCode">
          <el-input v-model="form.channelCode" placeholder="请输入货道编号" />
        </el-form-item>
        <el-form-item label="所属设备" prop="vmId">
          <el-select v-model="form.vmId" placeholder="请选择所属设备" @change="handleVmChange">
            <el-option
              v-for="item in vmList"
              :key="item.id"
              :label="item.innerCode + ' - ' + item.vmTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品ID" prop="skuId">
          <el-input-number v-model="form.skuId" :min="1" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="最大容量" prop="maxCapacity">
          <el-input-number v-model="form.maxCapacity" :min="1" :max="100" placeholder="请输入最大容量" />
        </el-form-item>
        <el-form-item label="当前容量" prop="currentCapacity">
          <el-input-number v-model="form.currentCapacity" :min="0" :max="form.maxCapacity" placeholder="请输入当前容量" />
        </el-form-item>
        <el-form-item label="上次补货时间" prop="lastSupplyTime">
          <el-date-picker
            v-model="form.lastSupplyTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Channel">
import { listChannel, getChannel, delChannel, addChannel, updateChannel } from "@/api/manage/channel";
import { listVendingMachine } from "@/api/manage/vendingMachine";

const { proxy } = getCurrentInstance();

const channelList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const vmList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    channelCode: null,
    innerCode: null,
    vmId: null
  },
  rules: {
    channelCode: [
      { required: true, message: "货道编号不能为空", trigger: "blur" }
    ],
    vmId: [
      { required: true, message: "所属设备不能为空", trigger: "blur" }
    ],
    maxCapacity: [
      { required: true, message: "最大容量不能为空", trigger: "blur" }
    ],
    currentCapacity: [
      { required: true, message: "当前容量不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询通道管理列表 */
function getList() {
  loading.value = true;
  listChannel(queryParams.value).then(response => {
    channelList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询设备列表 */
function getVmList() {
  listVendingMachine({}).then(response => {
    vmList.value = response.rows;
  });
}

// 获取进度条颜色
function getProgressColor(current, max) {
  const percentage = (current / max) * 100;
  if (percentage <= 20) return '#f56c6c'; // 红色 - 空货道
  if (percentage <= 50) return '#e6a23c'; // 橙色 - 需要补货
  return '#67c23a'; // 绿色 - 货物充足
}

// 获取容量状态
function getCapacityStatus(current, max) {
  const percentage = (current / max) * 100;
  if (percentage === 0) return 'danger';
  if (percentage <= 20) return 'warning';
  if (percentage <= 50) return 'info';
  return 'success';
}

// 获取容量状态文字
function getCapacityText(current, max) {
  const percentage = (current / max) * 100;
  if (percentage === 0) return '空货道';
  if (percentage <= 20) return '需要补货';
  if (percentage <= 50) return '货物较少';
  return '货物充足';
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    channelCode: null,
    skuId: null,
    vmId: null,
    innerCode: null,
    maxCapacity: null,
    currentCapacity: null,
    lastSupplyTime: null
  };
  proxy.resetForm("channelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加通道管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getChannel(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改通道管理";
  });
}

/** 设备变更处理 */
function handleVmChange(value) {
  const selectedVm = vmList.value.find(item => item.id === value);
  if (selectedVm) {
    form.value.innerCode = selectedVm.innerCode;
  }
}

/** 补货操作 */
function handleSupply(row) {
  proxy.$modal.confirm('确认要将货道 "' + row.channelCode + '" 补满货吗？').then(() => {
    const supplyData = {
      id: row.id,
      currentCapacity: row.maxCapacity,
      lastSupplyTime: new Date().toISOString()
    };
    return updateChannel(supplyData);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("补货成功");
  }).catch(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["channelRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateChannel(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addChannel(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除通道管理编号为"' + _ids + '"的数据项？').then(function() {
    return delChannel(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/channel/export', {
    ...queryParams.value
  }, `channel_${new Date().getTime()}.xlsx`)
}

getList();
getVmList();
</script>

<style scoped>
.ml-2 {
  margin-left: 8px;
}
</style>